package com.erastep.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.erastep.base.ConnectionFactory;
import com.erastep.base.SessionManager;
import com.erastep.pojo.BsMenus;
import com.erastep.pojo.Resource;
import com.erastep.pojo.User;
import com.erastep.util.CommonMethod;

import flex.messaging.FlexSessionManager;

public class Login {
	/**
	 * 系统用户登录
	 * @param user String
	 * @param pass String 
	 * @return json String 
	 * */
	public String login(String user,String pass){
		//System.out.println(SessionManager.getInstance().getSession().getId());
		String sql = "select * from userinfo u where u.loginname=?";
		Connection conn = ConnectionFactory.getDataConn();
		try {
			PreparedStatement pre = conn.prepareStatement(sql);
			pre.setString(1, user);
			ResultSet rs = pre.executeQuery();
			Boolean flg = false;
			User u = new User();
			ResultSet rsp = null;
			ResultSet rsp1 = null;
			ArrayList<Resource> rlist = new ArrayList<Resource>();
			ArrayList<BsMenus> rlist1 = new ArrayList<BsMenus>();
			while(rs.next()){
	            String password=rs.getString("password");
	            if(pass.trim().equals(password)){
	            	flg = true;
	            	CommonMethod.setDataByResultSet(rs,u);
	                Statement st = conn.createStatement();
	            	rsp = st.executeQuery("select p.* from pluginresource p,pluginrole pr where pr.pluginId=p.pid and pr.roleId="+u.getRid());
	            	while(rsp.next()){
		            	Resource r = new Resource();
		            	rlist.add((Resource)CommonMethod.setDataByResultSet(rsp,r));
	            	}
	            	rsp.close();
	            	rsp1 =  st.executeQuery("select b.* from pluginresource p,pluginrole pr,bsmenus b where pr.pluginId=p.pid and pr.roleId="+u.getRid()+" and b.systemid= p.systemid and b.formid=p.formid");
	            	while(rsp1.next()){
		            	BsMenus r = new BsMenus();
		            	rlist1.add((BsMenus)CommonMethod.setDataByResultSet(rsp1,r));
	            	}
	            	rsp1.close();
	            }
	        }
	        rs.close();
	        ConnectionFactory.closeConn(conn);
	        if(flg){
	        	try {
					return "{\"code\":\"1\",\"data\":"+CommonMethod.arrayObject(u,"password")+",\"plugins\":"+CommonMethod.FormartArray(rlist)+",\"menus\":"+CommonMethod.FormartArray(rlist1)+",\"message\":\"login success!\"}";
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }else{
	        	return "{\"code\":\"0\",\"data\":\"\",\"message\":\"login error!\"}";
	        }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "{\"code\":\"0\",\"data\":\"\",\"message\":\"login error!\"}";
	}
}
